#!/usr/bin/env ruby

unless (rpm_cmd = ARGV[0])
  STDERR.puts 'Usage: sign-rpm RPM_COMMAND'
  exit 1
end

password = '<%= passphrase %>'

require 'pty'

puts rpm_cmd
PTY.spawn(rpm_cmd) do |r, w, pid|
  # Older versions of rpmsign will prompt right away for the passphrase
  prompt = r.read(19)

  if prompt == 'Enter pass phrase: '
    STDOUT.puts prompt
    w.write("#{password}\n")
  end

  # Keep printing output unti the command exits
  loop do
    begin
      line = r.gets
      puts line
      if line =~ /Please enter the passphrase to unlock the OpenPGP secret key:/
        w.write("#{password}\n")
      elsif (line =~ /failed/) && !(line =~ /warning:/)
        STDERR.puts 'RPM signing failure'
        exit 1
      end
    rescue Errno::EIO
      break
    end
  end
end
